<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDateTime, formatImageUrl } from "@/utils/tools";
import {
  getAllStores,
  addStore,
  updateStore,
  deleteStore,
  getStoreEmployees,
  addEmployee,
  updateEmployee,
  deleteEmployee,
  getAllCostumes,
  updateCostume,
  addCostume,
  getAllCostumesForSelect,
  deleteCostume
} from "@/api/store";
import { Plus, PictureFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";

interface StoreData {
  id: string;
  name: string;
  address: string;
  phone: string;
  longitude: string;
  latitude: string;
  images: string[];
}

interface Employee {
  id: string;
  roleName: string;
  nickname: string;
  status: number;
  avatarUrl: string;
  count: string;
  phone: string;
}

interface StoreEmployees {
  photographers: Employee[];
  makeupArtists: Employee[];
}

const tableData = ref<StoreData[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("添加门店");
const formRef = ref();
const employeeDialogVisible = ref(false);
const employeeFormDialogVisible = ref(false);
const employeeFormTitle = ref("添加员工");
const currentStoreEmployees = ref<StoreEmployees>({
  photographers: [],
  makeupArtists: []
});
const currentStoreName = ref("");
const currentStoreId = ref("");
const employeeFormRef = ref();
const employeeFormData = reactive({
  id: "",
  phone: "",
  roleName: "photographer", // photographer or makeupArtist
  status: 0
});

const formData = reactive({
  id: "",
  name: "",
  address: "",
  phone: "",
  longitude: "",
  latitude: "",
  images: [] as string[]
});

const rules = {
  name: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
  address: [{ required: true, message: "请输入门店地址", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  longitude: [
    { required: true, message: "请输入经度", trigger: "blur" },
    {
      pattern:
        /^[\-\+]?(0?\d{1,2}(\.\d{1,6})?|1[0-7]?\d(\.\d{1,6})?|180(\.0{1,6})?)$/,
      message: "请输入正确的经度",
      trigger: "blur"
    }
  ],
  latitude: [
    { required: true, message: "请输入纬度", trigger: "blur" },
    {
      pattern: /^[\-\+]?([0-8]?\d(\.\d{1,6})?|90(\.0{1,6})?)$/,
      message: "请输入正确的纬度",
      trigger: "blur"
    }
  ]
};

const employeeRules = {
  phone: [
    { required: true, message: "请输入员工手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  roleName: [{ required: true, message: "请选择员工角色", trigger: "change" }]
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  formData.id = "";
  formData.images = [];
};

const handleAdd = () => {
  dialogTitle.value = "添加门店";
  dialogVisible.value = true;
  resetForm();
};

const handleEdit = (row: StoreData) => {
  dialogTitle.value = "编辑门店";
  dialogVisible.value = true;
  Object.assign(formData, row);
};

const handleDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm("确认删除该门店吗？此操作不可恢复", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await deleteStore(id);
    ElMessage.success("删除成功");
    getStoreList();
  } catch (error) {
    console.error("删除门店错误:", error);
  }
};

const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const api = formData.id ? updateStore : addStore;
        const result = await api(formData);
        ElMessage.success(formData.id ? "更新成功" : "添加成功");
        dialogVisible.value = false;
        getStoreList();
      } catch (error) {
        console.error(error);
        ElMessage.error(formData.id ? "更新失败" : "添加失败");
      }
    }
  });
};

const handleUploadSuccess = (response: any) => {
  if (response.code === 200) {
    formData.images.push(response.data);
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("图片上传失败");
  }
};

const handleRemoveImage = (index: number) => {
  formData.images.splice(index, 1);
};

const getStoreList = async () => {
  try {
    loading.value = true;
    const result = await getAllStores();
    tableData.value = result.data || [];
    if (tableData.value.length === 0) {
      ElMessage.info("暂无门店数据");
    }
  } catch (error) {
    console.error("获取门店列表错误:", error);
    ElMessage.error("获取门店列表失败");
  } finally {
    loading.value = false;
  }
};

const router = useRouter();

const handleCostumeManage = async (storeId: string, storeName: string) => {
  currentStoreId.value = storeId;
  currentStoreName.value = storeName;
  costumeDialogVisible.value = true;
  await getCostumeList();
};

const handleEmployeeManage = async (storeId: string, storeName: string) => {
  try {
    currentStoreName.value = storeName;
    currentStoreId.value = storeId;
    const result = await getStoreEmployees(storeId);
    currentStoreEmployees.value = result.data;
    employeeDialogVisible.value = true;
  } catch (error) {
    console.error("获取员工数据失败:", error);
    ElMessage.error("获取员工数据失败");
  }
};

const handleAddEmployee = () => {
  employeeFormTitle.value = "添加员工";
  employeeFormData.id = "";
  employeeFormData.phone = "";
  employeeFormData.roleName = "photographer";
  employeeFormData.status = 0;
  employeeFormDialogVisible.value = true;
};

const handleEditEmployee = (row: Employee) => {
  employeeFormTitle.value = "编辑员工";
  employeeFormData.id = row.id;
  employeeFormData.phone = row.phone || "";
  employeeFormData.roleName = row.roleName;
  employeeFormData.status = typeof row.status === "number" ? row.status : 0;
  employeeFormDialogVisible.value = true;
};

const handleDeleteEmployee = async (row: Employee) => {
  try {
    await ElMessageBox.confirm("确认删除该员工吗？此操作不可恢复", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await deleteEmployee(row.id);
    ElMessage.success("删除成功");
    const result = await getStoreEmployees(currentStoreId.value);
    currentStoreEmployees.value = result.data;
  } catch (error) {
    console.error("删除员工失败:", error);
    ElMessage.error("删除员工失败");
  }
};

const submitEmployeeForm = async () => {
  if (!employeeFormRef.value) return;

  await employeeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const api = employeeFormData.id ? updateEmployee : addEmployee;
        await api({
          ...employeeFormData,
          storeId: currentStoreId.value,
          avatarUrl: "default-avatar.png"
        });
        ElMessage.success(employeeFormData.id ? "更新成功" : "添加成功");
        employeeFormDialogVisible.value = false;
        const result = await getStoreEmployees(currentStoreId.value);
        currentStoreEmployees.value = result.data;
      } catch (error) {
        console.error(error);
        ElMessage.error(employeeFormData.id ? "更新失败" : "添加失败");
      }
    }
  });
};

// 切换员工状态
const toggleEmployeeStatus = async (
  row: Employee,
  value: string | number | boolean
) => {
  try {
    // 确保newStatus是数字类型
    const newStatus: number =
      value === true || value === "1" || value === 1 ? 1 : 0;
    await updateEmployee({
      id: row.id,
      status: newStatus,
      storeId: currentStoreId.value
    });

    ElMessage.success(`员工已${newStatus === 1 ? "上线" : "下线"}`);
  } catch (error) {
    // 如果失败，恢复原状态
    row.status =
      typeof row.status === "number"
        ? row.status === 1
          ? 0
          : 1
        : row.status === "1"
          ? 0
          : 1;
    console.error("切换员工状态失败:", error);
    ElMessage.error("切换员工状态失败");
  }
};

const costumeDialogVisible = ref(false);
const costumeFormDialogVisible = ref(false);
const costumeFormRef = ref();
const costumeFormData = reactive({
  costumesId: "",
  selectedCostumes: [] as string[]
});

const costumeSelectData = reactive({
  pageNo: 1,
  pageSize: 5,
  result: [],
  total: 0,
  totalPages: 0,
  filters: {
    name: "",
    costumeId: ""
  }
});

const costumeRules = {
  costumesId: [{ required: true, message: "请输入服饰ID", trigger: "blur" }]
};

const pageData = reactive({
  pageNo: 1,
  pageSize: 10,
  result: [],
  total: 0,
  totalPages: 0,
  start: 0,
  end: 0
});

const getCostumeList = async () => {
  try {
    loading.value = true;
    const { data } = await getAllCostumes(currentStoreId.value, {
      pageNo: pageData.pageNo,
      pageSize: pageData.pageSize
    });

    Object.assign(pageData, data);
  } catch (error) {
    console.error("获取服饰列表失败:", error);
    ElMessage.error("获取服饰列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageData.pageSize = val;
  pageData.pageNo = 1;
  getCostumeList();
};

const handleCurrentChange = (val: number) => {
  pageData.pageNo = val;
  getCostumeList();
};

const statusMap = {
  0: { label: "下架", type: "info" },
  1: { label: "上架", type: "success" }
};

// 切换服饰状态
const toggleCostumeStatus = async (row: any, value: any) => {
  try {
    const numValue = Number(value);
    await updateCostume({
      id: row.id,
      status: numValue
    });
    ElMessage.success(`服饰已${numValue === 1 ? "上架" : "下架"}`);
  } catch (error) {
    // 如果失败，恢复原状态
    row.status = row.status === 1 ? 0 : 1;
    console.error("切换服饰状态失败:", error);
    ElMessage.error("切换服饰状态失败");
  }
};

// 删除服饰
const handleDeleteCostume = async (row: any) => {
  try {
    await ElMessageBox.confirm("确认删除该服饰吗？此操作不可恢复", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const response = await deleteCostume(row.id);
    if (response?.data === true) {
      ElMessage.success("删除成功");
      getCostumeList(); // 刷新列表
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    console.error("删除服饰失败:", error);
    ElMessage.error("删除服饰失败");
  }
};

// 获取可选择的服饰列表
const getCostumesForSelect = async () => {
  try {
    loading.value = true;
    const res = await getAllCostumesForSelect({
      pageNo: costumeSelectData.pageNo,
      pageSize: costumeSelectData.pageSize,
      ...costumeSelectData.filters
    });
    if (res.data) {
      Object.assign(costumeSelectData, res.data);
    }
  } catch (error) {
    console.error("获取服饰列表失败:", error);
    ElMessage.error("获取服饰列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理筛选条件变化
const handleFilterChange = () => {
  costumeSelectData.pageNo = 1;
  getCostumesForSelect();
};

// 重置筛选条件
const resetFilters = () => {
  costumeSelectData.filters.name = "";
  costumeSelectData.filters.costumeId = "";
  handleFilterChange();
};

// 处理服饰选择分页
const handleSelectSizeChange = (val: number) => {
  costumeSelectData.pageSize = val;
  costumeSelectData.pageNo = 1;
  getCostumesForSelect();
};

const handleSelectCurrentChange = (val: number) => {
  costumeSelectData.pageNo = val;
  getCostumesForSelect();
};

// 打开新增服饰表单
const handleAddCostume = () => {
  costumeFormData.costumesId = "";
  costumeFormData.selectedCostumes = [];
  costumeFormDialogVisible.value = true;
  getCostumesForSelect();
};

// 提交新增服饰表单
const submitCostumeForm = async () => {
  console.log(
    "Submitting form with selected costumes:",
    costumeFormData.selectedCostumes
  );
  if (costumeFormData.selectedCostumes.length === 0) {
    ElMessage.warning("请选择要添加的服饰");
    return;
  }

  try {
    loading.value = true;
    const promises = costumeFormData.selectedCostumes.map(costumesId =>
      addCostume({
        storeId: currentStoreId.value,
        costumesId: costumesId.toString()
      })
    );

    const results = await Promise.allSettled(promises);
    const successCount = results.filter(result => {
      if (result.status === "fulfilled") {
        const response = result.value?.data;
        return response === "true";
      }
      return false;
    }).length;
    const failCount = results.length - successCount;

    if (successCount > 0) {
      ElMessage.success(`成功添加${successCount}个服饰`);
      if (failCount > 0) {
        ElMessage.warning(
          `${failCount}个服饰添加失败，可能是因为服饰已存在或其他原因`
        );
      }
      costumeFormDialogVisible.value = false;
      await getCostumeList(); // 等待列表刷新完成
    } else {
      ElMessage.error("添加服饰失败，请检查服饰是否已存在或稍后重试");
    }
  } catch (error: any) {
    console.error("添加服饰错误:", error);
    ElMessage.error(
      error?.response?.data?.message || "添加服饰失败，请稍后重试"
    );
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getStoreList();
});
</script>

<template>
  <div class="store-container">
    <el-card class="box-card">
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增门店
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        :empty-text="loading ? '加载中...' : '暂无数据'"
      >
        <el-table-column prop="id" label="门店编号" width="100" />
        <el-table-column prop="name" label="门店名称" min-width="180" />
        <el-table-column
          prop="address"
          label="门店地址"
          min-width="300"
          show-overflow-tooltip
        />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column label="门店图片" min-width="200">
          <template #default="{ row }">
            <el-image
              v-for="(img, index) in row.images"
              :key="index"
              :src="formatImageUrl(img)"
              style="width: 50px; height: 50px; margin-right: 5px"
              :preview-src-list="
                row.images.map((img: string) => formatImageUrl(img))
              "
              fit="cover"
              :preview-teleported="true"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><picture-filled /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="位置信息" width="200">
          <template #default="{ row }">
            <div>经度：{{ row.longitude }}</div>
            <div>纬度：{{ row.latitude }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="340" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              type="success"
              link
              @click="handleCostumeManage(row.id, row.name)"
            >
              服饰管理
            </el-button>
            <el-button
              type="warning"
              link
              @click="handleEmployeeManage(row.id, row.name)"
            >
              员工管理
            </el-button>
            <el-button type="danger" link @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑门店对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        destroy-on-close
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
          status-icon
        >
          <el-form-item label="门店名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入门店名称" />
          </el-form-item>
          <el-form-item label="门店地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入门店地址" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input
              v-model="formData.longitude"
              placeholder="请输入经度，范围：-180~180"
            />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input
              v-model="formData.latitude"
              placeholder="请输入纬度，范围：-90~90"
            />
          </el-form-item>
          <el-form-item label="门店图片">
            <el-upload
              action="/api/image"
              :on-success="handleUploadSuccess"
              :file-list="
                formData.images.map(img => ({
                  name: img,
                  url: formatImageUrl(img)
                }))
              "
              :on-remove="
                (file, fileList) => handleRemoveImage(fileList.indexOf(file))
              "
              list-type="picture-card"
              multiple
              accept="image/*"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="upload-tip">
                  支持 jpg、png、webp 格式，单张图片不超过 2MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 员工管理弹窗 -->
      <el-dialog
        v-model="employeeDialogVisible"
        :title="`${currentStoreName}员工管理`"
        width="800px"
        destroy-on-close
        class="employee-dialog"
      >
        <div class="toolbar">
          <el-button type="primary" @click="handleAddEmployee">
            <el-icon><Plus /></el-icon>
            新增员工
          </el-button>
        </div>

        <div class="employee-info">
          <div class="employee-group">
            <h3>摄影师 ({{ currentStoreEmployees.photographers.length }}人)</h3>
            <el-table :data="currentStoreEmployees.photographers" border>
              <el-table-column prop="nickname" label="姓名" />
              <el-table-column prop="phone" label="手机号" width="120" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-switch
                    v-model="row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="value => toggleEmployeeStatus(row, value)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="头像" width="80">
                <template #default="{ row }">
                  <el-avatar :size="40" :src="formatImageUrl(row.avatarUrl)" />
                </template>
              </el-table-column>
              <el-table-column prop="count" label="接单数" width="100" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="{ row }">
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteEmployee(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="employee-group">
            <h3>化妆师 ({{ currentStoreEmployees.makeupArtists.length }}人)</h3>
            <el-table :data="currentStoreEmployees.makeupArtists" border>
              <el-table-column prop="nickname" label="姓名" />
              <el-table-column prop="phone" label="手机号" width="120" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-switch
                    v-model="row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="value => toggleEmployeeStatus(row, value)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="头像" width="80">
                <template #default="{ row }">
                  <el-avatar :size="40" :src="formatImageUrl(row.avatarUrl)" />
                </template>
              </el-table-column>
              <el-table-column prop="count" label="接单数" width="100" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="{ row }">
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteEmployee(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>

      <!-- 员工表单弹窗 -->
      <el-dialog
        v-model="employeeFormDialogVisible"
        :title="employeeFormTitle"
        width="500px"
        destroy-on-close
        :close-on-click-modal="false"
      >
        <el-form
          ref="employeeFormRef"
          :model="employeeFormData"
          :rules="employeeRules"
          label-width="100px"
          status-icon
        >
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="employeeFormData.phone"
              placeholder="请输入员工手机号"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="员工角色" prop="roleName">
            <el-select
              v-model="employeeFormData.roleName"
              placeholder="请选择员工角色"
            >
              <el-option label="摄影师" value="photographer" />
              <el-option label="化妆师" value="makeupArtist" />
            </el-select>
          </el-form-item>
          <el-form-item label="在线状态">
            <el-select
              v-model="employeeFormData.status"
              placeholder="请选择在线状态"
            >
              <el-option label="离线" :value="0" />
              <el-option label="在线" :value="1" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="employeeFormDialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="submitEmployeeForm"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>

      <!-- 服饰管理弹窗 -->
      <el-dialog
        v-model="costumeDialogVisible"
        :title="`${currentStoreName} - 服饰管理`"
        width="1200px"
        destroy-on-close
        class="costume-dialog"
      >
        <div class="toolbar">
          <el-button type="primary" @click="handleAddCostume">
            <el-icon><Plus /></el-icon>
            新增服饰
          </el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="pageData.result"
          height="50vh"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="服饰名称" min-width="150" />
          <el-table-column
            prop="description"
            label="描述"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }"> ¥{{ row.price }} </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="value => toggleCostumeStatus(row, value)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" label="创建人" width="120" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" link @click="handleDeleteCostume(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pageData.pageNo"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pageData.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-dialog>

      <!-- 新增服饰表单弹窗 -->
      <el-dialog
        v-model="costumeFormDialogVisible"
        title="新增服饰"
        width="900px"
        height="75vh"
        destroy-on-close
        :close-on-click-modal="false"
        class="costume-form-dialog"
      >
        <div class="filter-container">
          <el-form :inline="true" :model="costumeSelectData.filters">
            <el-form-item label="服饰名称">
              <el-input
                v-model="costumeSelectData.filters.name"
                placeholder="请输入服饰名称"
                clearable
                @clear="handleFilterChange"
                @keyup.enter="handleFilterChange"
              />
            </el-form-item>
            <el-form-item label="服饰ID">
              <el-input
                v-model="costumeSelectData.filters.costumeId"
                placeholder="请输入服饰ID"
                clearable
                @clear="handleFilterChange"
                @keyup.enter="handleFilterChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFilterChange"
                >查询</el-button
              >
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          v-loading="loading"
          :data="costumeSelectData.result"
          border
          height="50vh"
          @selection-change="
            val => {
              costumeFormData.selectedCostumes = val.map(item => item.id);
              console.log(
                'Selected costumes:',
                costumeFormData.selectedCostumes
              );
            }
          "
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="服饰名称" min-width="150" />
          <el-table-column
            prop="description"
            label="描述"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }"> ¥{{ row.price }} </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" label="创建人" width="120" />
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="costumeSelectData.pageNo"
            v-model:page-size="costumeSelectData.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="costumeSelectData.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSelectSizeChange"
            @current-change="handleSelectCurrentChange"
          />
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="costumeFormDialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="submitCostumeForm"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.store-container {
  padding: 20px;

  .box-card {
    width: 100%;
  }

  .toolbar {
    margin-bottom: 20px;
  }

  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  .image-error {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: #f5f7fa;
    color: #909399;
  }

  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
  }

  .dialog-footer {
    text-align: right;
    margin-top: 16px;
  }

  :deep(.el-button--link) {
    padding: 0 8px;
    font-size: 14px;

    &:not(:last-child) {
      margin-right: 8px;
    }
  }
}

:deep(.employee-dialog) {
  .toolbar {
    margin-bottom: 20px;
  }

  .employee-info {
    .employee-group {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      h3 {
        font-size: 16px;
        margin: 0 0 12px;
        color: #303133;
      }
    }
  }
}

.costume-dialog {
  .toolbar {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .separator {
    margin: 0 8px;
    color: #909399;
  }

  :deep(.el-form--inline) {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.costume-form-dialog {
  :deep(.el-dialog) {
    height: 75vh;
    margin-top: 12.5vh !important;
    display: flex;
    flex-direction: column;

    .el-dialog__body {
      flex: 1;
      overflow-y: auto;
      padding: 0;
    }

    .filter-container {
      position: sticky;
      top: 0;
      z-index: 1;
      margin-bottom: 0;
      padding: 15px 20px;
      background-color: #fff;
    }

    .el-table {
      margin: 15px 20px;
      width: calc(100% - 40px);
    }

    .pagination-container {
      position: sticky;
      bottom: 0;
      background-color: #fff;
      padding: 15px 20px;
      margin-top: 0;
      border-top: 1px solid #dcdfe6;
    }
  }
}
</style>
